﻿#include "WebConfig.h"
#include "ui_WebConfig.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QDebug>
#include <QSettings>
#include <QTcpServer> 

#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif


bool setPHPini(QString phpIniPath, QString webroot,QString defaultIncludePath)
{
	QFile phpIniFile(phpIniPath);
	if (!phpIniFile.exists()){
		qDebug() << phpIniPath << "does't exist";
		return false;
	}
	
	if (!phpIniFile.open(QIODevice::ReadWrite)){
		qDebug() << "open php ini file fail";
		return false;
	}
	QString contentReplace;
	QString phpInclude;
	QSettings settings("web.ini", QSettings::IniFormat);
	QString phpIncludePath = settings.value("web/phpIncludePath").toString();
	contentReplace = defaultIncludePath;
	if (!phpIncludePath.isEmpty()){
		contentReplace = phpIncludePath;
	}
	qDebug() << "content replace:" << contentReplace;
	QByteArray content = phpIniFile.readAll();
	QString contentString = content;
	phpInclude = webroot;
	contentString.replace(contentReplace, phpInclude);
	//qDebug() << contentString;
	//phpIniFile.write(contentString.toLatin1());
	phpIniFile.flush();
	phpIniFile.close();

	phpIniFile.remove();

	QFile phpIniFileTarget(phpIniPath);

	if (!phpIniFileTarget.open(QIODevice::ReadWrite)){
		qDebug() << "open php ini file fail";
		return false;
	}

	phpIniFileTarget.write(contentString.toLatin1());
	phpIniFileTarget.flush();
	phpIniFileTarget.close();

	settings.setValue("web/phpIncludePath", phpInclude);
	return true;
}

WebConfig::WebConfig(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::WebConfig)
{
    setWindowFlags(Qt::FramelessWindowHint);
    setWindowModality(Qt::ApplicationModal);
    setAttribute(Qt::WA_DeleteOnClose);

#ifdef _DEBUG
	m_curDir = "D:/tools/dothing_server_manager";
#else
	m_curDir = QCoreApplication::applicationDirPath();
#endif

    ui->setupUi(this);
	ui->radioButtonPHP53->setVisible(false);
	ui->radioButtonPHP54->setVisible(false);
	ui->radioButtonPHP55->setVisible(false);
    flushUi();
}

WebConfig::~WebConfig()
{
    delete ui;
}

void WebConfig::flushUi(){

    QSettings settings("web_n.ini", QSettings::IniFormat);

    QString documentRoot = settings.value("web/documentRoot",m_curDir+"/www").toString();
    QString port = settings.value("web/port").toString();
	/*QString php = settings.value("web/defaultphp").toString();

	if (php == "53"){
		ui->radioButtonPHP53->setChecked(true);
	}
	else if (php == "54"){
		ui->radioButtonPHP54->setChecked(true);
	}
	else
	{
		ui->radioButtonPHP55->setChecked(true);
	}*/

    ui->lineEditPort->setText(port);
    ui->lineEditWebDocument->setText(documentRoot);
}

void WebConfig::on_pushButtonChooseWebDocument_pressed()
{
    QString flag = QStringLiteral("Web");
    QString dir = QFileDialog::getExistingDirectory(this,flag,
                                                    "/",
                                                    QFileDialog::ShowDirsOnly
                                                    | QFileDialog::DontResolveSymlinks);
    if(dir != ""){
        ui->lineEditWebDocument->setText(dir);
    }else{

    }
}

void WebConfig::on_pushButtonSave_pressed()
{
    QString port = ui->lineEditPort->text();
    QString documentRoot = ui->lineEditWebDocument->text();

    if(port == "" || documentRoot == ""){
        QMessageBox::warning(NULL,"提示","所有参数不能为空");
        return;
    }
	bool isNumber;
	port.toInt(&isNumber);
	if (!isNumber){
        QMessageBox::warning(NULL,"提示","端口只能是数字");
        return;
    }

    QDir dir(documentRoot);
    if(!dir.exists()){
        QMessageBox::warning(NULL,"提示","目录不存在");
        return;
    }
	QString phpIniFilePath;
	QString defaultPHPIncludePath;
    QString apache_conf = "ServerRoot \"%1\"\r\n";
            apache_conf += "DocumentRoot \"%2\"\r\n";
            apache_conf += "<Directory \"%3\">\r\n";
            apache_conf +=     "Options Indexes FollowSymLinks Includes ExecCGI\r\n";
            apache_conf +=     "AllowOverride All\r\n";
            apache_conf +=     "Require all granted\r\n";
            apache_conf += "</Directory>\r\n";
			apache_conf += "ServerName localhost:%4\r\n";
            apache_conf += "Listen %5\r\n";

			QSettings settings("web_n.ini", QSettings::IniFormat); // 当前目录的INI文件
			settings.beginGroup("web");
			settings.setValue("documentRoot", documentRoot);
			settings.setValue("port", port);
			/*
			if (ui->radioButtonPHP53->isChecked()){
				settings.setValue("defaultphp", 53);
				apache_conf += " Include \"conf/extra/httpd-dothing-pre.conf\"";
				phpIniFilePath = m_curDir+"/server/pre/php/php.ini";
				defaultPHPIncludePath = m_curDir + "/server/pre/php/PEAR";
			}
			else if (ui->radioButtonPHP54->isChecked()){
				settings.setValue("defaultphp", 54);
				apache_conf += " Include \"conf/extra/httpd-dothing-pre54.conf\"";
				phpIniFilePath = m_curDir + "/server/pre/php54/php.ini";
				defaultPHPIncludePath = m_curDir + "/server/pre/php54/PEAR";
			}
			else
			{
				settings.setValue("defaultphp", 55);
				apache_conf += " Include \"conf/extra/httpd-dothing.conf\"";
				phpIniFilePath = m_curDir + "/server/php/php.ini";
				defaultPHPIncludePath = m_curDir + "/server/php/PEAR";
			}
			*/
			/*if (!setPHPini(phpIniFilePath, documentRoot, defaultPHPIncludePath)){
				if (QMessageBox::Ok == QMessageBox::information(NULL, "提示", "修改失败")){
					close();
				}
				return;
			}*/
			settings.endGroup();
			QString conf = m_curDir + "/server/nginx/conf/nginx_tmpl.conf";
			QFile nginx(conf);
		

			if (!nginx.open(QIODevice::ReadOnly)){
				qDebug() << "open nginx conf tmpl file fail";
				return ;
			}
			QByteArray contentByte = nginx.readAll();
			QString content = contentByte;
			content.replace("$${port}", port);
			content.replace("$${document_root}", documentRoot);
			nginx.flush();
			nginx.close();


			QFile confTarget(m_curDir + "/server/nginx/conf/nginx.conf");

			if (!confTarget.open(QIODevice::WriteOnly)){
				qDebug() << "open nginx conf file fail";
				return ;
			}

			confTarget.write(content.toLatin1());
			confTarget.flush();
			confTarget.close();

   

    if(QMessageBox::Ok == QMessageBox::information(NULL,"提示","保存成功,web服务将会重启")){
		QString cmd = "net stop nginx";
		emit webConfigSetOverSignal(cmd);
        close();
    }
}

void WebConfig::on_pushButtonCheckPort_pressed()
{
	
	QString port = ui->lineEditPort->text();
	QTcpServer *pServer = new QTcpServer(this);
	if (pServer->listen(QHostAddress::Any, port.toUInt()))
	{
		QMessageBox::information(NULL, "提示", "端口可以使用");
		
	}
	else
	{
		QMessageBox::warning(NULL, "提示", "端口已经被占用");
	}
	pServer->deleteLater();
}

